package com.atguigu.gmallpublisher.controller;

import com.atguigu.gmallpublisher.service.SugarService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Collection;
import java.util.Map;
import java.util.Set;
import java.util.logging.SimpleFormatter;

//@Controller
@RestController
@RequestMapping("/sugar")
public class SugarController {

    @Autowired
    private SugarService sugarService;

    @RequestMapping("/test")
    //@ResponseBody
    public String test1() {
        System.out.println("111111111111");
        return "success";
    }

    @RequestMapping("/test2")
    public String test2(@RequestParam("name") String nn,
                        @RequestParam(value = "age", defaultValue = "18") int age) {
        System.out.println(nn + ":" + age);
        return "success";
    }

    @RequestMapping("/gmv")
    public String getGmv(@RequestParam(value = "date", defaultValue = "0") int date) {

        if (date == 0) {
            date = getToday();
        }

        //获取数据
        BigDecimal gmv = sugarService.getGmv(date);

        return "{\n" +
                "  \"status\": 0,\n" +
                "  \"msg\": \"\",\n" +
                "  \"data\": " + gmv +
                "}";
    }


    @RequestMapping("/trademark")
    public String getGmvByTm(@RequestParam(value = "date", defaultValue = "0") int date,
                             @RequestParam(value = "limit", defaultValue = "5") int limit) {

        if (date == 0) {
            date = getToday();
        }

        //查询数据
        Map gmvByTm = sugarService.getGmvByTm(date, limit);

        Set tmNames = gmvByTm.keySet();
        Collection tmGmvs = gmvByTm.values();

        return "{\n" +
                "  \"status\": 0,\n" +
                "  \"msg\": \"\",\n" +
                "  \"data\": {\n" +
                "    \"categories\": [\"" +
                StringUtils.join(tmNames, "\",\"") +
                "\"],\n" +
                "    \"series\": [\n" +
                "      {\n" +
                "        \"name\": \"品牌GMV\",\n" +
                "        \"data\": [\n" +
                StringUtils.join(tmGmvs, ",") +
                "        ]\n" +
                "      }\n" +
                "    ]\n" +
                "  }\n" +
                "}";
    }

    private int getToday() {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        return Integer.parseInt(sdf.format(System.currentTimeMillis()));
    }

}
